package cn.kgc.microservicecloudproviderdept8001.controller;

import cn.kgc.microservicecloudproviderdept8001.service.CategoryService;
import cn.kgc.pojo.Category;
import cn.kgc.pojo.ResultEntity;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author shkstart
 * @create 2020-03-09 11:27
 */
@RequestMapping("/provider/category")
@RestController
public class CategoryController {

    @Resource
    CategoryService categoryService;

    @Resource
    DiscoveryClient client;

    @RequestMapping("/list")
    public ResultEntity<List<Category>> list() {
        List<Category> all = categoryService.getAll();
        return ResultEntity.successWithoutData(all);
    }

    @RequestMapping("/get/{id}")
    public ResultEntity<Category> get(@PathVariable Integer id) {
        Category category = categoryService.getById(id);
        return ResultEntity.successWithoutData(category);
    }

    @RequestMapping("/update")
    public ResultEntity<String> update(@RequestBody Category category) {
        int i = categoryService.updateByPrimaryKey(category);
        if (i > 0) {
            return ResultEntity.successWithoutData();
        } else {
            return ResultEntity.failed("修改失败");
        }
    }

    @RequestMapping("/insert")
    public ResultEntity<String> insert(@RequestBody Category category) {
        int i = categoryService.insert(category);
        if (i > 0) {
            return ResultEntity.successWithoutData();
        } else {
            return ResultEntity.failed("添加失败");
        }
    }

    @RequestMapping("/delete/{id}")
    public ResultEntity<String> delete(@PathVariable Integer id) {
        int i = categoryService.deleteByPrimaryKey(id);
        if (i > 0) {
            return ResultEntity.successWithoutData();
        } else {
            return ResultEntity.failed("删除失败");
        }
    }
//服务发现（服务的查询） 对外开放一个查询微服务信息的通道
        @RequestMapping("/discovery")
    public Object discovery() {
        List<String> services = client.getServices();
        System.out.println("*****************************" + services);

        List<ServiceInstance> instances = client.getInstances("MICROSERVICECLOUD-PROVIDER-DEPT");
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getServiceId() + "\t" +
                    instance.getHost() + "\t" +
                    instance.getPort() + "\t"
                    + instance.getUri());
        }
        return this.client;
    }

}
